import React, { Component } from 'react';
import PropTypes from 'prop-types'

import { reqRoles } from '../../api/admin'

import {
  Form,
  Input,
  Select
} from 'antd'

const { Option } = Select;
class AddOrUpdateUser extends Component {

  state = {
    roleList: []
  }

  static propTypes = {
    setForm: PropTypes.func.isRequired,
    user: PropTypes.object
  }

  myRefAddUser = React.createRef()

  getAllRole = async () => {
    const result = await reqRoles()
    if (result.status === 0) {
      this.setState({
        roleList: result.data
      })
    }
  }

  UNSAFE_componentWillMount () {
    this.getAllRole()
  }

  componentDidMount () {
    this.props.setForm(this.myRefAddUser.current)
  }

  render () {
    const { roleList } = this.state
    const user = this.props.user
    const formItemLayout = {
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 15
      },
    };
    return (
      <Form
        ref={this.myRefAddUser}
        {...formItemLayout}
      >

        <Form.Item
          label='用户名'
          name="username"
          initialValue={user.username}
          rules={[
            {
              required: true,
              message: '请输入用户名!',
            },
          ]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>
        {
          user._id ? null : (
            <Form.Item
              label='密码'
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入密码!',
                },
              ]}
            >
              <Input type="password" placeholder="请输入密码" />
            </Form.Item>
          )
        }

        <Form.Item
          label='手机号'
          name="phone"
          initialValue={user.phone}
          rules={[
            {
              required: true,
              message: '请输入手机号!',
            },
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          label='邮箱'
          name="email"
          initialValue={user.email}
          rules={[
            {
              required: true,
              message: '请输入邮箱!',
            },
          ]}
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>
        <Form.Item
          label='角色'
          name="role_id"
          initialValue={user.role_id}
          rules={[
            {
              required: true,
              message: '请选择角色!',
            },
          ]}
        >
          <Select allowClear placeholder="请选择角色" >
            {
              roleList.map(item => {
                return (
                  <Option value={item._id} key={item._id}>{item.name}</Option>
                )
              })
            }
          </Select>
        </Form.Item>
      </Form>
    );
  }
}

export default AddOrUpdateUser;